<template>
  <div class="warning-alert">
    <!-- 添加搜索卡片 -->
    <el-card class="card-container search-card">
      <div class="search-container">
        <el-input v-model="searchParams.alertId" placeholder="请输入预警编号" clearable></el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>
    </el-card>

    <!-- 表格卡片 -->
    <el-card class="card-container table-card">
      <!-- 预警表格 -->
      <el-table :data="warningData" border class="custom-table rounded-table">
        <el-table-column prop="id" label="预警编号" min-width="120" />
        <el-table-column prop="createTime" label="预警时间" min-width="200" />
        <el-table-column prop="equipmentId" label="设备ID" min-width="120" />
        <el-table-column prop="robotId" label="机器人ID" min-width="120" />
        <!-- 新增维修人员列 -->
        <el-table-column label="维修人员" min-width="200">
          <template #default="scope">
            <div class="maintenance-person-cell">
              <span v-if="scope.row.maintenancePerson.length > 0">{{ scope.row.maintenancePerson.join(',') }}</span>
              <span v-else class="text-muted">未分配</span>
              <el-button type="text" size="small" @click="openPersonSelectDialog(scope.row)">选择</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
          :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 选择维修人员弹窗 -->
    <el-dialog v-model="personSelectDialogVisible" title="指派维修人员" width="400px">
      <div class="dialog-content">
        <!-- 添加调试信息 -->
        <p v-if="currentRow">当前行数据: {{ currentRow }}</p>

        <el-form-item label="指派人员ID" prop="userId" :rules="[{ required: true, message: '请输入维修人员ID', trigger: 'blur' }]">
          <el-input v-model="assignForm.userId" placeholder="请输入维修人员ID" type="number" />
        </el-form-item>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="personSelectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPersonSelection">确定指派</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
// 修改导入语句，添加ElMessage
import { ElTable, ElTableColumn, ElButton, ElDialog, ElCheckboxGroup, ElCheckbox, ElPagination, ElMessage } from 'element-plus';
import request from '@/utils/request';

export default {
  name: 'WarningAlert',
  components: {
    ElTable,
    ElTableColumn,
    ElButton,
    ElDialog,
    ElCheckboxGroup,
    ElCheckbox,
    ElPagination  // 注册分页组件
  },
  setup() {
    // 预警表格数据
    const warningData = ref([]);
    // 添加完整数据存储，用于搜索过滤
    const allWarningData = ref([]);
    // 添加搜索参数
    const searchParams = ref({
      alertId: ''
    });
    // 分页相关参数
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);

    // 维修人员列表 - 删除虚拟数据
    const maintenancePersons = ref([]);
    // 添加加载状态
    const isLoading = ref(false);

    // 弹窗状态和选中的维修人员
    const personSelectDialogVisible = ref(false);
    const selectedPersons = ref([]);
    const currentRow = ref(null);
    // 获取预警数据
    const getWarningData = async () => {
      try {
        const response = await request.get('/admin/showAlerts', {
          params: {
            page: currentPage.value,
            pageSize: pageSize.value
          }
        });
        if (response.code === 200) {
          const alertData = response.data || [];
          const formattedData = alertData.map(item => ({
            ...item,
            id: item.id || item.alertId || item.warningId,
            maintenancePerson: item.maintenancePerson || []
          }));
          // 保存完整数据用于搜索
          allWarningData.value = formattedData;
          // 初始显示所有数据
          warningData.value = formattedData;
          total.value = response.total || 0;
        } else {
          console.error('获取预警数据失败:', response.msg);
          ElMessage.error(`获取数据失败: ${response.msg || '未知错误'}`);
        }
      } catch (error) {
        console.error('请求预警数据出错:', error);
        // 错误处理：清空表格数据避免渲染异常
        warningData.value = [];
        total.value = 0;
      }
    };

    // 组件挂载时获取数据
    onMounted(() => {
      getWarningData();
    });

    // 添加指派表单数据
    const assignForm = ref({
      userId: ''
    });

    // 打开选择维修人员弹窗时初始化表单
    const openPersonSelectDialog = (row) => {
      // 修改验证逻辑，只检查row是否存在，不严格验证id
      if (!row) {
        ElMessage.warning('请选择有效的预警记录');
        return;
      }
      currentRow.value = row;
      assignForm.value.userId = getCurrentUserId() || '';
      personSelectDialogVisible.value = true;
    };

    // 确认指派时使用表单数据
    const confirmPersonSelection = async () => {
      if (!currentRow.value) {
        ElMessage.warning('请选择有效的预警记录');
        return;
      }

      if (!assignForm.value.userId) {
        ElMessage.warning('请输入维修人员ID');
        return;
      }

      try {
        const response = await request.get('/admin/alertUser', {
          // 将参数包装在params对象中
          params: {
            alertsId: currentRow.value.id,
            userId: assignForm.value.userId
          }
        });

        if (response.code === 200) {
          ElMessage.success('指派成功');
          personSelectDialogVisible.value = false;
          getWarningData(); // 刷新预警列表
        } else {
          ElMessage.error(`指派失败: ${response.msg || '未知错误'}`);
        }
      } catch (error) {
        console.error('指派维修人员请求失败:', error);
        ElMessage.error('网络错误，无法完成指派');
      }
    };

    // 分页事件处理
    const handleSizeChange = (val) => {
      pageSize.value = val;
      getWarningData();
    };

    const handleCurrentChange = (val) => {
      currentPage.value = val;
      getWarningData();
    };

    // 获取当前用户ID
    const getCurrentUserId = () => {
      // 从localStorage获取用户信息，实际项目中可能需要从全局状态管理获取
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
      return userInfo.id || '';
    };

    // 添加搜索方法
    const handleSearch = () => {
      const searchValue = searchParams.alertId.trim();
      if (!searchValue) {
        // 搜索框为空时显示所有数据
        warningData.value = [...allWarningData.value];
        total.value = allWarningData.value.length;
      } else {
        // 精确匹配预警编号
        warningData.value = allWarningData.value.filter(item =>
          item.id.toString() === searchValue
        );
        total.value = warningData.value.length;
      }
      // 重置到第一页
      currentPage.value = 1;
    };

    return {
      warningData,
      allWarningData,
      searchParams,
      maintenancePersons,
      personSelectDialogVisible,
      selectedPersons,
      openPersonSelectDialog,
      confirmPersonSelection,
      // 分页相关返回值
      currentPage,
      pageSize,
      total,
      handleSizeChange,
      handleCurrentChange,
      getCurrentUserId,
      assignForm // 添加这一行，暴露assignForm对象给模板
    };
  }
};
</script>

<style scoped>
/* 添加卡片容器样式 */
.card-container {
  width: 70%;
  margin: 0 auto 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
  /* 添加盒模型设置 */
}

/* 搜索卡片样式 */
.search-card {
  padding: 20px;
  /* 与表格卡片保持相同内边距 */
}

/* 表格卡片样式 */
.table-card {
  padding: 20px;
}

/* 搜索容器样式 */
.search-container {
  display: flex;
  align-items: center;
  gap: 10px;
  /* 移除额外内边距，使用卡片统一内边距 */
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 20px;
  text-align: center;
  position: static;
  bottom: auto;
  left: auto;
  transform: none;
  background-color: transparent;
  padding: 0;
  box-shadow: none;
}

/* 表格行样式 */
::v-deep .el-table .table-row:hover {
  background-color: #1890ff !important;
  color: #fff !important;
  font-size: 15px !important;
  font-weight: 500;
  position: relative;
  z-index: 10 !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2) !important;
  transform: scale(1.015);
  transform-origin: center left;
}

/* 表头样式 */
::v-deep .custom-table .el-table__header-wrapper .el-table__header {
  background-color: #1890ff !important;
}

::v-deep .custom-table .el-table__header th {
  background-color: #1890ff !important;
  color: #fff !important;
  border-bottom: 2px solid white !important;
}

/* 表格圆角样式 */
::v-deep .rounded-table {
  border-radius: 12px !important;
  overflow: hidden !important;
  border: none !important;
}

/* 表头圆角 */
::v-deep .rounded-table .el-table__header-wrapper {
  border-radius: 12px 12px 0 0 !important;
  overflow: hidden !important;
}

/* 修复表格行高度问题 */
::v-deep .el-table__body-wrapper {
  overflow: visible !important;
}

::v-deep .el-table__row {
  height: auto !important;
}

::v-deep .el-table .cell {
  transition: padding 0.3s ease !important;
}

::v-deep .el-table .table-row:hover .cell {
  padding: 14px 15px !important;
}

/* 原有样式保留但去除冲突部分 */
.warning-alert {
  padding: 20px 0;
}

.maintenance-person-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.dialog-content {
  padding: 0 20px;
}

.el-form-item {
  margin-bottom: 20px;
  margin-top: 10px;
}

/* 添加搜索容器样式 */
.search-container {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 20px;
}

/* 确保搜索输入框适当宽度 */
.search-container .el-input {
  width: 300px;
}
</style>
